<template>
  <Drawer :closable="false" :visible="visible" :width="720" title="上传升级回滚文件">
    <Form
      ref="form"
      :wrapperCol="{ span: 8 }"
      layout="horizontal"
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
    >
      <FormItem
        :rules="{ required: true, message: '请选择应用', trigger: 'blur' }"
        label="选择应用"
        name="appId"
        required
      >
        <Select
          v-model:value="formState.appId"
          @select="getTenants"
          :options="appOptions.map((app) => ({ value: app.id, label: app.name }))"
          style="width: 200px"
        >
        </Select>
      </FormItem>

      <FormItem
        :rules="{ required: true, message: '请选择租户', trigger: 'blur' }"
        label="选择租户"
        name="tenantId"
        required
      >
        <Select
          v-model:value="formState.tenantId"
          @select="getDatabase"
          :options="tenantsOptions.map((tenant) => ({ value: tenant.id, label: tenant.name }))"
        >
        </Select>
      </FormItem>

      <FormItem :label-col="{ span: 4 }" label="升级文件" name="file">
        <Upload
          name="file"
          :max-count="1"
          :before-upload="beforeUpload"
          v-model:file-list="formState.fileList"
          :headers="{ 'Content-Type': 'multipart/form-data' }"
          @change="handleUpgradeFileChange"
        >
          <Button>
            <UploadOutlined />
            点击上传升级文件
          </Button>
        </Upload>
      </FormItem>

      <FormItem name="rollbackFile" :label-col="{ span: 4 }" label="回滚文件">
        <Upload
          name="rollbackFile"
          :max-count="1"
          :before-upload="beforeUpload"
          v-model:file-list="formState.rollbackFileList"
          :headers="{ 'Content-Type': 'multipart/form-data' }"
          @change="handleRollbackFileChange"
        >
          <Button>
            <UploadOutlined />
            点击上传回滚文件
          </Button>
        </Upload>
      </FormItem>

      <FormItem label="升级方式" name="type" :label-col="{ span: 4 }">
        <RadioGroup v-model:value="formState.type" :options="typeOptions" />
      </FormItem>

      <FormItem label="描述" name="description" :label-col="{ span: 4 }">
        <Textarea v-model:value="formState.description" placeholder="请输入升级任务描述" :rows="3" />
      </FormItem>
      <div class="w-full">
        <DbInfoCard v-bind:dbInfo="dbInfo"></DbInfoCard>
      </div>
    </Form>
    <template #footer>
      <Button class="float-right" type="primary" @click="onSubmit">确认上传</Button>
      <Button class="float-right mr-10px" @click="closeDrawer">取消</Button>
    </template>
  </Drawer>
</template>

<script lang="ts" setup>
import { Form, FormItem, Select, RadioGroup, Upload, Button, Input } from 'ant-design-vue';
import { reactive, ref } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { getAppForTenants, getTenantListByApp } from '../../../api/upgrade-center/upgradeForm';
import { AppItem, TenantItem } from '../../../api/upgrade-center/model/upgradeFormModel';
import { getDbInfo, uploadSqlFile } from '../../../api/upgrade-center/datastore/upgradeDb';
import { DbInfo } from '../../../api/upgrade-center/model/upgradeDbModel';
import { useMessage } from '/@/hooks/web/useMessage';
import { Drawer } from 'ant-design-vue';
import DbInfoCard from './DbInfoCard.vue';

const emits = defineEmits(['gotDbInfo', 'uploadSuccess']);
const form = ref(null);
const { createMessage } = useMessage();
const Textarea = Input.TextArea;
interface FormState {
  tenantId: string;
  appId: string;
  type: number;
  file: any;
  rollbackFile: any;
  description: string;
  fileList: [];
  rollbackFileList: [];
}

const formState: FormState = reactive({
  tenantId: '',
  appId: '',
  type: 1,
  file: '',
  rollbackFile: '',
  description: '',
  fileList: [],
  rollbackFileList: [],
});

let appOptions = ref<AppItem[]>([]);
let tenantsOptions = ref<TenantItem[]>([]);
let dbInfo = ref<Partial<DbInfo>>('');
const visible = ref(false);

const typeOptions = ref([
  { label: '数据库升级', value: 1 },
  { label: '数据库及应用升级', value: 2 },
]);

const getApp = async () => {
  appOptions.value = await getAppForTenants();
};

const getTenants = async () => {
  tenantsOptions.value = await getTenantListByApp({ appId: formState.appId });
};

const getDatabase = async () => {
  dbInfo.value = await getDbInfo({
    appId: formState.appId,
    tenantId: formState.tenantId,
  });
  dbInfo.value.appId = formState.appId;
  dbInfo.value.tenantId = formState.tenantId;
  emits('gotDbInfo', dbInfo.value);
};

// 限制最多只能上传一个文件，且取最新上传的
const handleUpgradeFileChange = (files) => {
  let newFileList = [...files.fileList];
  newFileList = newFileList.slice(-1);
  formState.fileList = newFileList;
};

const handleRollbackFileChange = (files) => {
  let newFileList = [...files.fileList];
  newFileList = newFileList.slice(-1);
  formState.rollbackFileList = newFileList;
};

const onSubmit = async () => {
  try {
    await form.value.validate();
    let file;
    let rollbackFile;

    if (formState.fileList.length === 0) {
      const errorMessage = { message: '请上传升级文件' };
      throw errorMessage;
    } else {
      file = formState.fileList[0].originFileObj;
    }

    if (formState.rollbackFileList.length > 0) {
      rollbackFile = formState.rollbackFileList[0].originFileObj;
    }
    const res = await uploadSqlFile({
      data: {
        appId: formState.appId,
        tenantId: formState.tenantId,
        type: formState.type,
        description: formState.description,
      },
      file: file,
      rollbackFile: rollbackFile,
    });
    if (res.data.data === '上传成功') {
      createMessage.success('数据库升级/回滚文件上传成功');
      setTimeout(function () {
        emits('uploadSuccess', true);
        visible.value = false;
      }, 500);
    } else {
      createMessage.error(res.data.errorMsg);
      emits('uploadSuccess', false);
    }
  } catch (error) {
    if (typeof error === 'string') createMessage.warning(error);
    emits('uploadSuccess', false);
  }
};
getApp();
const beforeUpload = () => {
  return false;
};
const openDrawer = async (params: any) => {
  visible.value = true;
  formState.appId = params.appId;
  getTenants();
  formState.tenantId = params.tenantId;
};
const closeDrawer = () => {
  visible.value = false;
  form.value.resetFields();
};

defineExpose({ openDrawer, closeDrawer });
</script>

<style lang="less" scoped></style>
